using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Data.DTO.Hmw;
using net_work.Data.Entity.Hmw;
using net_work.IRepository.Cou;
using net_work.IRepository.Hmw;
using net_work.IRepository.System;
using net_work.IService.Hmw;

namespace net_work.Service.Cou;

public class HomeworkService(
    ITransactionManager transactionManager,
    IHomeworkRepository homeworkRepository,
    ITeachingRepository teachingRepository,
    IHomeworkQuestionRepository homeworkQuestionRepository)
    : IHomeworkService
{
    public async Task<PagedResult<Homework>> GetHomeworksPagedAsync(PagedRequest request)
    {
        return await homeworkRepository.GetPagedAsync(request);
    }


    public Task<Homework?> SelectByIdAsync(long homeworkId)
    {
        return homeworkRepository.GetByIdAsync(homeworkId);
    }

    public async Task<long> InsertHomework(HomeworkAddRequest homeworkAddRequest)
    {
        var teaching = await teachingRepository.GetByIdAsync(homeworkAddRequest.TeachId);
        if (teaching == null)
        {
            return -1;
        }

        if (homeworkAddRequest.Deadline <= homeworkAddRequest.BeginTime)
        {
            return -1;
        }

        return await homeworkRepository.InsertAsync(homeworkAddRequest);
    }

    public async Task<int> UpdateHomework(HomeworkUpdateRequest homeworkUpdateRequest)
    {
        if (homeworkUpdateRequest.Id <= 0)
        {
            return -1;
        }

        var teaching = await teachingRepository.GetByIdAsync(homeworkUpdateRequest.TeachId);
        if (teaching == null)
        {
            return -1;
        }

        if (homeworkUpdateRequest.Deadline <= homeworkUpdateRequest.BeginTime)
        {
            return -1;
        }

        try
        {
            await transactionManager.BeginTransactionAsync();

            if (homeworkUpdateRequest.HomeworkQuestionIds is { Count: > 0 })
            {
                var homeworkQuestionIds = homeworkUpdateRequest.HomeworkQuestionIds;
                var oldList =
                    await homeworkQuestionRepository.GetPagedAsync(new PagedRequest(1, PageSizeEnum.Unlimited,
                        [new FilterCondition("HomeworkId", FilterOperator.Equals, homeworkUpdateRequest.Id)]));

                if (oldList.TotalRecords > 0)
                {
                    var oldIds = oldList.Data.Select(o => o.Id).ToList();
                    var idsToRemove = oldIds.Except(homeworkQuestionIds).ToList();
                    var idsToAdd = homeworkQuestionIds.Except(oldIds).ToList();

                    if (idsToRemove.Count != 0)
                    {
                        if (!await homeworkQuestionRepository.DeleteByIdsAsync(idsToRemove))
                        {
                            throw new Exception("删除旧的多余的作业题目失败");
                        }
                    }

                    if (idsToAdd.Count != 0)
                    {
                        if (await homeworkQuestionRepository.InsertAsync(new HomeworkQuestionAddRequest
                            {
                                HomeworkId = homeworkUpdateRequest.Id,
                                BankQuestionIds = idsToAdd
                            }) <= 0)
                        {
                            throw new Exception("添加新的作业题目失败");
                        }
                    }
                }
                else
                {
                    if (await homeworkQuestionRepository.InsertAsync(new HomeworkQuestionAddRequest
                        {
                            HomeworkId = homeworkUpdateRequest.Id,
                            BankQuestionIds = homeworkQuestionIds
                        }) <= 0)
                    {
                        throw new Exception("添加新的作业题目失败");
                    }
                }
            }

            await homeworkRepository.UpdateAsync(homeworkUpdateRequest);

            await transactionManager.CommitTransactionAsync();
        }
        catch (Exception e)
        {
            await transactionManager.RollbackTransactionAsync();
            return -1;
        }
        
        return 1;
    }

    public async Task<int> DeleteHomeworkByIds(List<long> ids)
    {
        return await homeworkRepository.DeleteByIdsAsync(ids) ? 1 : -1;
    }

    public async Task<int> Release(long homeworkId)
    {
        if (homeworkId <= 0)
        {
            return -1;
        }

        var pagedResult = await homeworkQuestionRepository.GetPagedAsync(new PagedRequest(1, PageSizeEnum.Unlimited, [
            new FilterCondition("HomeworkId", FilterOperator.Equals, homeworkId)
        ]));
        if (pagedResult.TotalRecords <= 0)
        {
            return -1;
        }

        return await homeworkRepository.Release(homeworkId) ? 1 : -1;
    }
}